﻿using System.Windows.Controls;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GlobalData;
using Microsoft.Extensions.DependencyInjection;
using Model.Core.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static Mysqlx.Crud.Order.Types;

namespace RobotPratolSolution.ViewModels
{
    public class MangeDeviceViewModel : ObservableObject
    {

        private bool _isMoving = false;
        //  private DispatcherTimer _speedTimer;
        // private double[] _currentSpeed = new double[2] { 0,0};
        private readonly object _speedLock = new object();

        private readonly HashSet<string> _activeDirections = new();

        public RelayCommand<string> MoveCommand { get; set; }

        CloudMqClientCtrl _mqClientCtrl { get; set; }
        MqTopics _GlobalMqTopics { get; set; }
        LocalRobotInfo LocalRobotInfo { get; set; }

        public MangeDeviceViewModel()
        {
            //_speedTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) };
            //_speedTimer.Tick += SpeedTimer_Tick;
            _mqClientCtrl = App.ServiceProvider.GetService<CloudMqClientCtrl>();
            _GlobalMqTopics = App.ServiceProvider.GetService<MqTopics>();
            LocalRobotInfo = App.ServiceProvider.GetService<LocalRobotInfo>();

            MoveCommand = new RelayCommand<string>(direction =>
            {
                var validDirections = new[] { "StartUp", "StartDown", "StartLeft", "StartRight" };
                if (direction != null&& direction.StartsWith("Start"))
                {            
                    if (validDirections.Contains(direction))
                      StartMove(direction.Substring(5));
                    else
                        Console.WriteLine($"无效移动方向: {direction}");
                }
                else if (direction == "Stop")
                {
                    StopMove();
                }
            });


            _mqClientCtrl.MsgReceivedEvent += (a, b) =>
            {

                if (_GlobalMqTopics.RobotStatusTopic.Equals(a))
                {
                    JObject jsondata = JsonConvert.DeserializeObject<JObject>(b);

                    foreach (var item in jsondata)
                    {
                        string name = item.Key;
                        string value = item.Value.ToString();
                        switch (name)
                        {
                            case "GreenLightEquipment":
                                GreenLightStatus = value;
                                break;
                            case "RedLightEquipment":
                                RedLightStatus = value;
                                break;
                            case "RotationEquipment":
                                SpinMotorStatus = value;
                                break;
                            case "LiftingEquipment":
                                MotorStatus = value;
                                break;
                            case "BellEquipment":
                                AlarmBellStatus = value;
                                break;
                        }
                    }
                }
                else if (_GlobalMqTopics.RobotPointStatusTopic.Equals(a))
                {
                    JObject jsondata = JsonConvert.DeserializeObject<JObject>(b);
                    X = Convert.ToDouble(jsondata["x"]);
                    Y = Convert.ToDouble(jsondata["y"]);
                    Z = Convert.ToDouble(jsondata["z"]);
                }
                else if (_GlobalMqTopics.RobotWheelStatusTopic.Equals(a))
                {
                    JObject jsondata = JsonConvert.DeserializeObject<JObject>(b);
                    ControlMode = jsondata["control_mode"]?.ToString();
                    EmergencyStopPressed = Convert.ToBoolean(jsondata["emergency_stop_pressed"]);
                }
                else if(_GlobalMqTopics.RobotBatteryStatus_Topic.Equals(a))
                {
                    JObject jsondata = JsonConvert.DeserializeObject<JObject>(b);
                    BatteryInfo = new BatteryInfo
                    {
                        IsCharge = Convert.ToBoolean(jsondata["ischarge"]),
                        Num = Convert.ToInt32(jsondata["num"])
                    };
                    // 处理电池信息
                }
                else if (_GlobalMqTopics.Job_Status_Topic.Equals(a))
                {
                    JObject jsondata = JsonConvert.DeserializeObject<JObject>(b);
                    JobStatus= jsondata["status"]?.ToString();
                }

            };

            //MyNavicationCtl.Instance.RobotPointInfoCallBack += (a, b, c) =>
            //{
            //    X = a;
            //    Y=b; 
            //};
        }

        public void LoadBaseInfo()
        {
            RobotType = LocalRobotInfo.RobotType;
        }

        public void AddSubTopic()
        {
            _ = _mqClientCtrl.AddSubTopic(_GlobalMqTopics.RobotStatusTopic);
            _ = _mqClientCtrl.AddSubTopic(_GlobalMqTopics.RobotPointStatusTopic);
            _ = _mqClientCtrl.AddSubTopic(_GlobalMqTopics.RobotWheelStatusTopic);
            _ = _mqClientCtrl.AddSubTopic(_GlobalMqTopics.RobotBatteryStatus_Topic);
            _ = _mqClientCtrl.AddSubTopic(_GlobalMqTopics.Job_Status_Topic);
        }
        public void DeleteSubTopic()
        {
            _ = _mqClientCtrl.UnsubscribeAsync(_GlobalMqTopics.RobotStatusTopic);
            _ = _mqClientCtrl.UnsubscribeAsync(_GlobalMqTopics.RobotPointStatusTopic);
            _ = _mqClientCtrl.UnsubscribeAsync(_GlobalMqTopics.RobotWheelStatusTopic);
            _ = _mqClientCtrl.UnsubscribeAsync(_GlobalMqTopics.RobotBatteryStatus_Topic);
            _ = _mqClientCtrl.UnsubscribeAsync(_GlobalMqTopics.Job_Status_Topic);
        }
        /// <summary>
        /// 绿灯控制
        /// </summary>
        /// <param name="isOpen"></param>
        public void GreenLightManage(bool isOpen)
        {
            JObject jsondata = new JObject();
            jsondata.Add("name", "GreenLightEquipment");
            string data = isOpen ? "on" : "off";
            jsondata.Add("value", data);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotCommandTopic, jsondata.ToString());
        }
        /// <summary>
        /// 红灯控制
        /// </summary>
        /// <param name="isOpen"></param>
        public void RedLightManage(bool isOpen)
        {
            JObject jsondata = new JObject();
            jsondata.Add("name", "RedLightEquipment");
            string data = isOpen ? "on" : "off";
            jsondata.Add("value", data);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotCommandTopic, jsondata.ToString());
        }
        /// <summary>
        /// 旋转电机
        /// </summary>
        /// <param name="isOpen"></param>
        public void SpinMotorManage(bool isOpen)
        {
            JObject jsondata = new JObject();
            jsondata.Add("name", "RotationEquipment");
            string data = isOpen ? "on" : "off";
            jsondata.Add("value", data);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotCommandTopic, jsondata.ToString());
        }
        public void MotorManage(int ctrltype)
        {
            JObject jsondata = new JObject();
            jsondata.Add("name", "LiftingEquipment");
            string data = string.Empty;
            switch (ctrltype)
            {
                case 1: data = "up"; break;
                case 2: data = "down"; break;
                case 3: data = "stop"; break;
            }
            jsondata.Add("value", data);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotCommandTopic, jsondata.ToString());
        }

        public void AlarmBellManage(bool isOpen)
        {
            JObject jsondata = new JObject();
            jsondata.Add("name", "BellEquipment");
            string data = isOpen ? "on" : "off";
            jsondata.Add("value", data);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotCommandTopic, jsondata.ToString());
        }

        //private void SpeedTimer_Tick(object sender, EventArgs e)
        //{
        //    lock (_speedLock)
        //    {
        //        if (_activeDirections.Count == 0) return;

        //        var direction = _activeDirections.Last().Substring(5);
        //        //var speedIndex = direction switch
        //        //{
        //        //    "Up" or "Down" => 0,
        //        //    "Left" or "Right" => 1,
        //        //    _ => -1
        //        //};
        //        //if (speedIndex != -1)
        //        //{
        //        //    _currentSpeed[speedIndex] = Math.Min(Math.Abs(_currentSpeed[speedIndex]) + 0.05, 0.3) * (direction switch
        //        //    {
        //        //        "Up" or "Right" => 1,
        //        //        "Down" or "Left" => -1,
        //        //        _ => 0
        //        //    });
        //        //}
        //        MovSpeedCtrl("Start", direction);
        //    }
        //}

        public void StartMove(string direction)
        {
            Console.WriteLine($"[{DateTime.Now}]:开始移动=>{direction.ToLower()}");
            MovSpeedCtrl("Start", direction.ToLower());
        }

        public void StopMove()
        {
            Console.WriteLine($"[{DateTime.Now}]:停止移动");
            MovSpeedCtrl("Stop", null);

        }

        internal void MovSpeedCtrl(string isstart, string direction)
        {
            JObject jsondata = new JObject();
            jsondata.Add("command", isstart);
            jsondata.Add("type", direction);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.Move_Topic, jsondata.ToString());
        }



        internal void WheelStateCtrl(string? tag)
        {
            JObject jsondata = new JObject();
            jsondata.Add("command", tag);
            _mqClientCtrl.SendMessageAsync(_GlobalMqTopics.RobotWheelCommandTopic, jsondata.ToString());
        }


        private string _JobStatus;

        public string JobStatus
        {
            get { return _JobStatus; }
            set { 
                _JobStatus = value;
                OnPropertyChanged();
            }
        }



        private BatteryInfo _BatteryInfo;

        public BatteryInfo BatteryInfo
        {
            get { return _BatteryInfo; }
            set { 
                _BatteryInfo = value; 
                OnPropertyChanged();
            }
        }


        private string _RobotType;
        public string RobotType
        {
            get => _RobotType;
            set { _RobotType = value; 
                OnPropertyChanged();
            }
        }

        private string _GreenLightStatus;

        public string GreenLightStatus
        {
            get { return _GreenLightStatus; }
            set { 
                _GreenLightStatus = value; OnPropertyChanged();
            }
        }
        private string _RedLightStatus;

        public string RedLightStatus
        {
            get { return _RedLightStatus; }
            set { 
                _RedLightStatus = value; OnPropertyChanged();
            }
        }
        private string _SpinMotorStatus;

        public string SpinMotorStatus
        {
            get { return _SpinMotorStatus; }
            set { 
                _SpinMotorStatus = value; OnPropertyChanged();
            }
        }

        private string _MotorStatus;

        public string MotorStatus
        {
            get { return _MotorStatus; }
            set {
                _MotorStatus = value; OnPropertyChanged();
            }
        }

        private string _AlarmBellStatus;

        public string AlarmBellStatus
        {
            get => _AlarmBellStatus;
            set { 
                _AlarmBellStatus = value; OnPropertyChanged();
            }
        }
        private double _X;
        public double X
        {
            get { return _X; }
            set { _X = value; OnPropertyChanged(); }
        }

        private double _Y;
        public double Y
        {
            get { return _Y; }
            set { _Y = value; OnPropertyChanged(); }
        }
        private double _Z;
        public double Z
        {
            get { return _Z; }
            set { _Z = value; OnPropertyChanged(); }
        }

        private string _ControlMode = "";
        public string ControlMode
        {
            get => _ControlMode;
            set
            {
                _ControlMode = value;
                OnPropertyChanged();
            }
        }

        private bool _EmergencyStopPressed;
        public bool EmergencyStopPressed
        {
            get => _EmergencyStopPressed;
            set { _EmergencyStopPressed = value; OnPropertyChanged(); }
        }
    }


    public class BatteryInfo
    {
        /// <summary>
        /// 是否在充电
        /// </summary>
       public bool IsCharge { get; set; }
        /// <summary>
        /// 电池电量
        /// </summary>
        public int Num { get; set; }
    }
}
